iconv = require 'iconv-lite'
# Iconv  = require('iconv').Iconv
http = require 'http'
https = require 'https'
qs = require 'querystring'
events = (require 'events').EventEmitter
url = require 'url'
T = require './lib/tools.coffee'
fs = require 'fs'



class Request extends events
    constructor:()->
        @u2 = null
        # @urlQueue = [] 
    request:(urlS,callback)=>
        # console.log urlString
        # if @urlQueue.length is 0 then return
            # urlS = @urlQueue.shift()
        if typeof urlS is 'string'
            urlObj = url.parse(urlS)
        else
            urlObj = urlS
        # console.log urlObj.protocol
        if urlObj.protocol == 'http:'
            protocolReq = http.request
            urlObj.port = 80
        else if urlObj.protocol == 'https:'
            protocolReq = https.request
            urlObj.port = 443
        # console.log protocolReq,urlObj
        # console.log urlS,urlObj
        urlObj.method = 'GET'
        if !callback
            callbck = ()->
                return
        T.log url.format urlS
        req = protocolReq(urlObj, (res)=> 
            # @emit 'onFetchstart', url.parse(urlS),req
            # console.log("Got response: " + res.statusCode, res.headers)
            if(res.statusCode is 301 or res.statusCode is 302)
                @u2= res.headers.location
                if (@u2.indexOf 'http://') isnt 0 and (@u2.indexOf 'https://') isnt 0
                    @u2 = urlObj.protocol+'//'+ urlObj.host + decodeURIComponent(res.headers.location)
                console.log urlS + '  forword to  '+ @u2
                # @emit 'onFetchredirect' ,url.parse(urlS),@u2,res
                @request @u2,callback
            buffers = []
            size = 0
            # console.log c++
            res
            .on('data', (buffer)=> 
                buffers.push(buffer)
                size += buffer.length
            )
            .on('end', ()=> 
                T.logEnd url.format urlS
                responseBuffer = new Buffer size
                pos = 0;
                try
                    if buffers.length isnt 0
                        # console.log (res.headers['content-type'].match /charset=(\w|\s|-|\d)*/)[0].toLowerCase()
                        @charset =  (res.headers['content-type'].match /charset=(\w|\s|-|\d)*/)[0].toLowerCase()
                        @charset = @charset.split('=')[1]
                        # console.log 123213213213, @charset
                        for i in [0..buffers.length-1]
                            buffers[i].copy responseBuffer, pos
                            pos += buffers[i].length
                    # T.logEnd urlS
                        if typeof urlS is 'string'
                            callback url.parse(urlS),responseBuffer,res 
                        else
                            callback urlS,responseBuffer,res
                catch e
                    console.log e
                    # errStr = JSON.stringify e
                    # throw new Error()

                # @emit 'onFetchComplete',url.parse(urlS),responseBuffer,res
            )

        )
        req.on('error', (e)=>
            # @emit 'onFetchclienterror',e
            console.log("Got error: " + e.message)
            # @request urlS,callback
            console.log urlS
            # throw e
            # request urlS,callback
        )
        # req.write('')
        req.end()


            # console.log socket
        # @urlQueue.push(urlString)


req = new Request()
# _url = 'http://top.etao.com/?tbpm=20131216'
_url = 'http://shu.taobao.com/trendindex?query=api'
# _url = 'http://shu.taobao.comhttps://login.taobao.com/member/login.jhtml?from=taobaoindex&sub=true&redirect_url=http://shu.taobao.com/login/callback'
dataPath = './data/t.log'
delFile if (fs.unlinkSync dataPath if fs.existsSync dataPath)
req.request _url ,(urlObj,responseBuffer,res)->
    str = iconv.decode responseBuffer,req.charset
    fs.appendFileSync dataPath,str